const path = require('path')
const resolve = dir => path.join(__dirname, dir)

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development'

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 匹配gzip压缩的资源
const productionGzipExtensions = ['html', 'js', 'css']

// 本地环境是否需要使用cdn
const devNeedCdn = true

// cdn链接
const cdn = {
  // cdn：模块名称和模块作用域命名（对应window里面挂载的变量名称）
  externals: {
    vue: 'Vue',
    vuex: 'Vuex',
    'vue-router': 'VueRouter',
    axios: 'axios',
    'element-ui': 'ELEMENT',
    $: 'jQuery',
    jquery: 'jQuery',
    'windows.jquery': 'jQuery',
    Aliplayer: 'Aliplayer'
  },
  // cdn的css链接
  css: [
    'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-ui/2.15.6/theme-chalk/index.min.css',
    'https://g.alicdn.com/apsara-media-box/imp-web-player/2.24.1/skins/default/aliplayer-min.css' // 阿里云播放器css
  ],
  // cdn的js链接
  js: [
    'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.14/vue.min.js',
    'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue-router/3.2.0/vue-router.min.js',
    'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vuex/3.5.1/vuex.min.js',
    'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/axios/0.19.2/axios.min.js',
    'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-ui/2.15.6/index.js',
    'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js', // jquery库
    '//view.csslcloud.net/js/sdk/3.7.4/liveSDK.js', // cc直播
    '//view.csslcloud.net/js/sdk/3.7.4/playbackSDK.js',
    'https://g.alicdn.com/apsara-media-box/imp-web-player/2.24.1/aliplayer-min.js', // 阿里云播放器js
    'https://p.bokecc.com/player?newversion=true' // CC播放器js
  ]
}

// 可视化分析图谱
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

module.exports = {
  productionSourceMap: false,
  chainWebpack: config => {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')
    // 移除 preload 插件
    config.plugins.delete('preload')
    // 压缩代码
    config.optimization.minimize(true)
    // 分割代码
    config.optimization.splitChunks({
      chunks: 'all'
    })
    // 添加别名
    config.resolve.alias
      .set('vue$', 'vue/dist/vue.esm.js')
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@components', resolve('src/components'))
      .set('@views', resolve('src/views'))
      .set('@router', resolve('src/router'))
      .set('@store', resolve('src/store'))

    // ============注入cdn start============
    config.plugin('html').tap(args => {
      // 生产环境或本地需要cdn时，才注入cdn
      args[0].title = process.env.VUE_APP_TITLE
      if (isProduction || devNeedCdn) args[0].cdn = cdn
      return args
    })
    // ============注入cdn end============

    // ============压缩图片 start============
    // config.module
    //   .rule('images')
    //   .use('image-webpack-loader')
    //   .loader('image-webpack-loader')
    //   .options({ bypassOnDebug: true })
    //   .end()
    // ============压缩图片 end============
  },
  configureWebpack: config => {
    // 用cdn方式引入，则构建时要忽略相关资源
    if (isProduction || devNeedCdn) config.externals = cdn.externals
    // 生产环境相关配置
    if (isProduction) {
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        })
      )
      // config.plugins.push(new BundleAnalyzerPlugin())
    }
    config.performance = {
      hints: 'warning',
      // 入口起点的最大体积
      maxEntrypointSize: 50000000,
      // 生成文件的最大体积
      maxAssetSize: 30000000,
      // 只给出 js 文件的性能提示
      assetFilter: function(assetFilename) {
        return assetFilename.endsWith('.js')
      }
    }
    config.module.rules.push({
      test: /\.html$/,
      include: path.resolve(__dirname, 'src'),
      use: [
        {
          loader: 'html-loader',
          options: {
            interpolate: true
          }
        }
      ]
    })
  },
  devServer: {
    overlay: {
      // 让浏览器 overlay 同时显示警告和错误
      warnings: true,
      errors: true
    },
    open: true,
    host: '0.0.0.0', // 设置主机地址
    port: 8080, // 设置默认端口
    https: false,
    hotOnly: false, // 热更新
    // 设置代理
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API,
        secure: false,
        changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
        // ws: true, // 是否启用websockets
        pathRewrite: {
          '^/api': '/'
        }
      }
    }
  },
  css: {
    loaderOptions: {
      scss: {
        // 向全局sass样式传入共享的全局变量, $src可以配置图片cdn前缀 background: url($src+"/images/500.png"); $src: "${process.env.VUE_APP_BASE_API}";
        // 详情: https://cli.vuejs.org/guide/css.html#passing-options-to-pre-processor-loaders
        prependData: `
        @import "@/styles/var.scss";
        @import "@/styles/theme.scss";
        @import "@/styles/mixin.scss";
        `
      }
    }
  },
  outputDir:
    process.env.NODE_ENV === 'development' ? './build/dist' : './build/' + process.env.NODE_ENV,
  assetsDir: 'static',
  indexPath: 'index.html'
}
